# -*- coding:utf-8 -*-

import socket
import functools

import tornado.ioloop

import busmanager
import config

_socket = None
_ioloop = tornado.ioloop.IOLoop.instance()

def start():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setblocking(0)
    sock.bind(("127.0.0.1", config.UDP_PORT))
    global _socket
    _socket = sock
    _ioloop.add_handler(_socket.fileno(), _read_callback, _ioloop.READ)

def _read_callback(fd, events):
    b, _ = _socket.recvfrom(1024)
    busmanager.handle_bus_message(b)
       
if __name__=="__main__":
    start()
    tornado.ioloop.IOLoop.instance().start()
    
    
        
